#!/usr/bin/env python

# ical2vcal.cgi by Charl P. Botha http://cpbotha.net/
# based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/273844
# integrated work by Mark Graves for VCS file downloading (much better
# than copying and pasting!)

import cgi
# enable cgi traceback manager.
import cgitb; cgitb.enable()
import os, sys
import vcal

HTML_TEMPLATE = \
"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>ical2vcal</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head><body><h1>ical2vcal</h1>

<p>Use this neat little CGI to convert ICAL files, for example exported from
Google Calendar, to VCAL version 1 files, that can be for example imported
into the Palm Desktop 4.x software.  In other words, use this to import Google
Calendars into Palm Desktop, okay?  For more info, go to <a
href="http://cpbotha.net/2007/04/26/google-calendar-to-palm-desktop-conversion/">http://cpbotha.net/2007/04/26/google-calendar-to-palm-desktop-conversion/</a>.
Please leave a comment on the linked blog post if you use this CGI, even if it
doesn't work.  </p>

<p>Click the "Browse" button to select an ICS file on your side, then click on
the "Convert to VCAL" button to convert to a VCS file.  You'll get a
VCS file that you should import into Palm Desktop with File | Import.
</p>

<p>
Oh by the way, you use this script ENTIRELY AT YOUR OWN RISK. :)
</p>

<form action="%(SCRIPT_NAME)s" method="POST" enctype="multipart/form-data">
File name: <input name="ical_file" type="file">
<input name="submit" type="submit" value="Convert to VCAL">
</form>
</body>
</html>"""

def print_html_form ():
    """This prints out the html form. Note that the action is set to
      the name of the script which makes this is a self-posting form.
      In other words, this cgi both displays a form and processes it.
    """
    print "content-type: text/html\n"
    print HTML_TEMPLATE % {'SCRIPT_NAME':os.environ['SCRIPT_NAME']}
    
def process_ical_file(form_field):
           
    form = cgi.FieldStorage()
    if not form.has_key(form_field):
        return False
    
    fileitem = form[form_field]
    if not fileitem.file:
        return False

    icsfilename = fileitem.filename
    name_only = os.path.splitext(icsfilename)[0]
    vcsfilename = name_only + ".vcs"

    # first read everything into buffer
    chunks = []
    while 1:
        chunk = fileitem.file.read(100000)
        if not chunk:
            break
        else:
            chunks.append(chunk)

    cbuffer = ''.join(chunks)

    try:
        cal = vcal.parse(cbuffer)
        # see http://www.phpbuilder.com/columns/chow20021007.php3?page=4
        # for the example I pulled the headers from.
        print "Content-Type: text/x-vCalendar"
        print "Content-Disposition: inline; filename=" + vcsfilename + "\n"
        print cal.as_vcal()
        
    except Exception, e:
        print "content-type: text/plain\n"
        print "Error parsing your upload: %s" % (str(e),)

    return True

if not process_ical_file("ical_file"):
    print_html_form ()
